package com.hxy.hrm.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hxy.hrm.domain.KillCourse;
import com.hxy.hrm.mapper.KillCourseMapper;
import com.hxy.hrm.service.IKillCourseService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.netflix.discovery.converters.Auto;
import org.apache.commons.lang.time.DateUtils;
import org.redisson.Redisson;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hxy
 * @since 2022-01-20
 */
@Service
public class KillCourseServiceImpl extends ServiceImpl<KillCourseMapper, KillCourse> implements IKillCourseService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private KillCourseMapper KillCourseMapper;

    @Override
    public void publishKillCourse2Redis() {

        // 查询所有满足条件的课程
        EntityWrapper<KillCourse> wrapper = new EntityWrapper<>();
        Date now = new Date();
        //添加时间
        Date afterTwoDayTime = DateUtils.addDays(now,2);
        wrapper.eq("kill_status",KillCourse.KILL_STATUS_WILL_PUBLISH)
                .and().between("start_time",now,afterTwoDayTime);

        // 查询的课程
        List<KillCourse> killCourses = KillCourseMapper.selectList(wrapper);
        logger.info("查询到的课程，{}",killCourses);
        killCourses.forEach(killCourse -> {
            // 生成秒杀码
            killCourse.setKillCode(UUID.randomUUID().toString());
            // 将课程信息存到redis中
            Boolean success = redisTemplate.opsForHash().putIfAbsent("kill_course",killCourse.getId().toString(),killCourse);
            // 如果成功就存入redis预热
            if (success) {
                logger.info("课程信息成功缓存预热，{}",killCourse.getCourseName());
                RSemaphore semaphore = redissonClient.getSemaphore("kill_course_" + killCourse.getId());
                boolean success1 = semaphore.trySetPermits(killCourse.getKillCount());
                if (success1) {
                    logger.info("课程库存成功缓存预热，{}",killCourse.getCourseName());
                    // 修改状态为已发布
                    killCourse.setKillStatus(KillCourse.KILL_STATUS_PUBLISHED);
                    KillCourseMapper.updateById(killCourse);
                } else {
                    logger.info("课程信息成功缓存预热失败，{}",killCourse.getCourseName());
                    // 如果失败将缓存信息回滚
                    redisTemplate.opsForHash().delete("kill_course_" + killCourse.getId());
                }
            }
        });



    }
}
